<?php
namespace app\services;

use app\providers\facade\RedisFacade;
use GuzzleHttp\Client as GuzzleClient;
use Ramsey\Uuid\Uuid;
use think\Log;

class HoistringMachine
{
    private static $baseUrl = 'https://fbox360.com';

    private $client;

    /**
     * HoistringMachine constructor.
     * @param $client
     */
    public function __construct()
    {
        $this->client = new GuzzleClient([
            'base_uri' => self::$baseUrl,
            'timeout'  => 5,
        ]);
    }

    /**
     * 登录
     * @return mixed|null
     */
    public function login() {
        $uri = '/idserver/core/connect/token';
        $params = [
            'username' => '18310255763',
            'password' => 'orit123456',
            'scope' => 'openid offline_access fbox email profile',
            'client_id' => 'hdtj',
            'client_secret' => 'a8579b2e4fcdfaff93c5284c435c68f4',
            'grant_type' => 'password',
        ];

        try{
            $resp = $this->client->post($uri, [
                'form_params' => $params,
            ]);
            $res = $resp->getBody()->getContents();
            if($resp->getStatusCode() != 200) {
                return null;
            }
            return json_decode($res, true);
        }catch(\Exception $e){
            return null;
        }
    }

    /**
     * 刷新token
     * @return mixed|null
     */
    public function refreshToken($userInfo)
    {
        $uri = '/idserver/core/connect/token';

        $token = RedisFacade::get('other_token_'.$userInfo['id']);
        $token = json_decode($token, true);
        if(empty($token) || empty($token['refresh_token'])){
            return null;
        }
        $params = [
            'refresh_token' => $token['refresh_token'],
            'scope' => 'openid offline_access fbox email profile',
            'client_id' => 'hdtj',
            'client_secret' => 'a8579b2e4fcdfaff93c5284c435c68f4',
            'grant_type' => 'refresh_token',
        ];
        try{
            $resp = $this->client->post($uri, [
                'form_params' => $params,
            ]);
            $res = $resp->getBody()->getContents();
            if($resp->getStatusCode() != 200) {
                return null;
            }
            return json_decode($res, true);
        }catch(\Exception $e){
            return null;
        }
    }

    /**
     * 列表
     */
    public function fBoxList($userInfo) {
        $uri = '/api/client/box/grouped';
        $token = RedisFacade::get('other_token_'.$userInfo['id']);
        $token = json_decode($token, true);
        for($i = 0; $i < 2; $i++){
            try{
                if(empty($token) || empty($token['refresh_token']) || $i == 1){
                    $token = $this->login();
                    RedisFacade::set('other_token_'.$userInfo['id'], json_encode($token));
                    RedisFacade::expireat('other_token_'.$userInfo['id'], time()+7200);
                }
                if(empty($token) || empty($token['refresh_token'])){
                    return null;
                }
                $resp = $this->client->get($uri, [
                    'headers' => [
                        'Authorization' => "Bearer ".$token['access_token'],
                        'X-FBox-ClientId' => Uuid::uuid3(Uuid::NAMESPACE_URL, $userInfo['username'])->toString(),
                    ]
                ]);
                $res = $resp->getBody()->getContents();
                if($resp->getStatusCode() == 200) {
                    return json_decode($res, true);
                }elseif($i > 0){
                    return null;
                }
            }catch(\Exception $e){
                Log::error($e->__toString());
            }
        }
        return null;
    }
}